package WebSocket;

import javax.websocket.ClientEndpoint;
import javax.websocket.ContainerProvider;
import javax.websocket.Session;
import javax.websocket.WebSocketContainer;
import java.io.IOException;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

@ClientEndpoint

public class WebSocketTest {
    private String deviceId;

    private Session session;

    public WebSocketTest() {
    }

    public WebSocketTest(String deviceId) {
        this.deviceId = deviceId;

    }

    protected boolean start() {
        WebSocketContainer Container = ContainerProvider.getWebSocketContainer();

//        String uri = "ws://localhost:9995/koala-socket-message/websocket/KoalaMaintainApp/" + deviceId;
        String uri = "ws://socket.dev.cloud.52koala.cn/koala-socket-message/websocket/KoalaMaintainApp/" + deviceId;

        System.out.println("Connecting to " + uri);

        try {
            session = Container.connectToServer(WebSocketTest.class, URI.create(uri));
            
            System.out.println("count: " + deviceId);

        } catch (Exception e) {
            e.printStackTrace();

            return false;

        }

        return true;

    }
    protected void close() throws IOException {
        this.session.close();
    }


    public static void main(String[] args) throws InterruptedException, IOException {
        List<WebSocketTest> list = new ArrayList<>();
        for (int i = 1; i < 5; i++) {
            WebSocketTest wSocketTest = new WebSocketTest(String.valueOf(i));
            
            list.add(wSocketTest);
            if (!wSocketTest.start()) {
                System.out.println("测试结束！");
                break;

            }

        }
        Scanner sc = new Scanner(System.in);
        sc.nextLine();
        for (WebSocketTest webSocketTest : list) {
            webSocketTest.close();
        }
        
    }

}
